package com.leyou.item.service;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.leyou.common.pojo.PageResult;
import com.leyou.item.mapper.BrandMapper;
import com.leyou.item.pojo.Brand;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.List;

@Service
public class BrandService {
    @Autowired
    private BrandMapper brandMapper;


    public PageResult<Brand> page(Integer page, Integer rows, String sortBy, Boolean desc, String key) {
        PageHelper.startPage(page,rows);
        //创建brand对象用来操作动态sql
        Example example = new Example(Brand.class);

        //动态判断key的值,如果有则根据key动态查询模糊查询name
        if(StringUtils.isNotBlank(key)){
            Example.Criteria criteria = example.createCriteria(); //需要where就创建
            criteria.andLike("name","%"+key+"%");
        }


        if (StringUtils.isNotBlank(sortBy)){
            //方法相当于写好order by
            example.setOrderByClause(sortBy+(desc?" desc":" asc"));
        }

        List<Brand> brands = brandMapper.selectByExample(example);
        //构造方法为 public PageInfo(List<T> list)
        PageInfo<Brand> pageInfo = new PageInfo<>(brands);

        return new PageResult<>(pageInfo.getTotal(),new Long(pageInfo.getPages()),brands);
        //Page<Brand> brandPage =(Page<Brand>) brandMapper.selectByExample(example);


    }

    @Transactional
    public void addBrand(Brand brand, List<Long> cids) {
        //直接保存品牌,并回显id
        //insertSelective和insert区别:
        brandMapper.insertSelective(brand);

        //循环保存品牌和分类的对应关系
        for (Long cid : cids) {
            brandMapper.insertCategoryBrand(cid,brand.getId());
        }

    }

    /**
     * 修改品牌,涉及到分类的修改,由于之前的分类可能在可能不再,所以直接删除这个品牌对应的所有的分类,重新添加
     * @param brand
     * @param cids
     */
    @Transactional
    public void updateBrand(Brand brand, List<Long> cids) {
        //品牌由于有id,所以可以直接修改
        brandMapper.updateByPrimaryKeySelective(brand);

        //先删除之前品牌对应的所有的分类,然后重新添加
        brandMapper.deleteCategoty(brand.getId());

        //循环保存品牌和分类的对应关系
        for (Long cid : cids) {
            brandMapper.insertCategoryBrand(cid,brand.getId());
        }
    }

    @Transactional
    public void deleteBrand(Long bid) {
        //先删除之前品牌对应的所有的分类,然后重新添加
        brandMapper.deleteCategoty(bid);
        brandMapper.deleteByPrimaryKey(bid); //根据key 删除
    }
}
